//
//  ViewController.swift
//  Notepad
//
//  Created by 左忠飞 on 2021/1/18.
//

import UIKit

class ViewController: UIViewController,HomeButtonDelegate {
    
    var homeView:HomeView?
    var dataArray:Array<String>?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "点滴生活"
        
        ////取消导航栏对页面布局的影响
        self.edgesForExtendedLayout = UIRectEdge()
        
        dataArray = DataManager.getGroupData()
        
        self.installUI()
    }


    func installUI() {
        //对home属性进行实例化
        homeView = HomeView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height - 64))
        homeView!.homeButtonDelegate = self
        self.view.addSubview(homeView!)
        
        //创建测试分组
        homeView?.dataArray = dataArray
        homeView?.updateLayout()
        self.installNavigationItem()
    }
    
    func installNavigationItem() {
        //创建导航功能按钮,将其风格设置为添加风格
        let barButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addGroup))
        self.navigationItem.rightBarButtonItem = barButtonItem
    }
    
    @objc func addGroup() {
        //创建UIAlertController
        let alertController = UIAlertController(title: "添加记事分组", message: "添加的分组名不能与已有的分组重复或为空", preferredStyle: .alert)
        alertController.addTextField { (textField) in
            textField.placeholder = "请输入记事分组名称"
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确定", style: .default) { [self] (UIAlertAction) in
            //进行有效性判断
            var exist = false
            self.dataArray?.forEach({ (element) in
                //如果分组已经存在,或者用户输入为空
                if (element == alertController.textFields?.first?.text) || ((alertController.textFields?.first?.text!.count)! == 0){
                    exist = true
                }
            })
            if exist {
                return
            }
            //将用户添加的分组名称追加进dataArray中
            self.dataArray?.append((alertController.textFields?.first?.text!)!)
            //刷新homeView
            self.homeView?.dataArray = self.dataArray
            self.homeView?.updateLayout()
            
            //将添加的分组写入数据库
            DataManager.saveGroup(name: (alertController.textFields?.first?.text!)!)
        }
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func homeButtonClick(title: String) {
        let controller = NoteLiistTVC()
        controller.name = title
        controller.dataUpdated = {
            self.dataArray = DataManager.getGroupData()
            self.homeView?.dataArray = self.dataArray
            self.homeView?.updateLayout()
        }
        self.navigationController?.pushViewController(controller,animated:true)
    }
    
}

